const requestSender = require('request-promise-native');
async function verifyGoogleIdToken(id_token) {
    //拿到idToken之后和google换取实际用户信息，这个过程同时会检查idToken的合法性
    var idTokenOptions = {
        method: 'GET',
        uri: 'https://oauth2.googleapis.com/tokeninfo?id_token='+id_token,
        headers: {
            'Content-Type' : 'application/json'
        },
        proxy: 'http://localhost:7890', //代理
        json: true
    };
    try{
        var idResult = await requestSender(idTokenOptions);
        if(!idResult.error){
            return { success: true, tokenContent: idResult };
        }
        /*
        {
            "iss": "https://accounts.google.com",
            "azp": "10554****7767-fpqtl0dr8v1mujers3****so2nskq6lc.apps.googleusercontent.com",
            "aud": "10554****7767-fpqtl0dr8v1mujers3****so2nskq6lc.apps.googleusercontent.com",
            "sub": "1110305*****623661931",
            "email": "fb-dtalker@foxmail.com",
            "email_verified": "true",
            "at_hash": "tvLpn6mRFxfnEuWbcrkzlg",
            "iat": "1673943122",
            "exp": "1673946722",
            "alg": "RS256",
            "kid": "d37aa5043812937fe43960ca3cf0e2284b6fc34d",
            "typ": "JWT"
        }
        或者
        {
            "error": "invalid_token",
            "error_description": "Invalid Value"
        }
        */
    }catch(err){
        console.log(err);
    }
    return { success: false, description: "Invalid Token" };
}


var urlencode = require('urlencode');

const router = require('koa-router')();
router.prefix('/login/third')

const GoogleConfig = {
    client_id : "105548****767-fpqtl0dr8v1mujers3****so2nskq6lc.apps.googleusercontent.com",
    client_secret : "GOC**X-Zr_euKCM51****NtdRFLRThRdap"
}

//点击Google第三方访问
router.get("/google/req", async(ctx, next)=>{
    let path = "https://accounts.google.com/o/oauth2/v2/auth?client_id="+GoogleConfig.client_id+
                    "&scope="+urlencode("https://www.googleapis.com/auth/userinfo.email")+
                    "&response_type=code"+
                    "&redirect_uri="+urlencode("http://localhost:3000/login/third/google/callback");
    ctx.redirect(path);
});

//接收Google回调
router.get('/google/callback', async(ctx, next)=>{
    console.log(ctx.query);  //{code: '4/0AWgavdezrj79BXK-ygDAlKC4b6N7oG0vSCLKDO15EsSGD12PCTxOfMYBJLslKMzVtCfi6A', scope: 'email https://www.googleapis.com/auth/userinfo.email openid', authuser: '0', prompt: 'none'}
    const code = ctx.query.code;

    //请求access_token的request
    var tokenOptions = {
        method: 'POST',
        uri: 'https://oauth2.googleapis.com/token',
        body: {
            code: code, //使用code
            client_id: GoogleConfig.client_id,
            client_secret: GoogleConfig.client_secret,
            grant_type: "authorization_code",
            redirect_uri: "http://localhost:3000/login/third/google/callback"
        },
        headers: {
            'Content-Type' : 'application/json'
        },
        proxy: 'http://localhost:7890', //谷歌需要kexue上网
        json: true
    };
    try{
        var tokenResponse = await requestSender(tokenOptions);
    }catch(err){
        console.log(err);
    }
    var access_token = tokenResponse.access_token; //用于申请其他服务的access_token
    var id_token = tokenResponse.id_token;
    console.log(tokenResponse);
    /*
    {
        access_token: 'ya29.a0AX9GBdWDUmPrNgPxeYyXDa-4YqIjvSEfriOA****lfhivo-ZVL9F2cGyhM9d6DRLLukfZDK_JhVRaBOxZYh*****2wtqOMHMxdZttyD5a_G7Upnrt3B5GMQJAUBoxUtjXreCycpMTolaZfYsuVxJWDGgD4e1aCgYKAa4SAQ8SFQHUCsbCHVc7S2QkY6Dl0GVNXqpNkw0163',
        expires_in: 3591,
        scope: 'https://www.googleapis.com/auth/userinfo.email openid',
        token_type: 'Bearer',
        id_token: 'eyJhbGciOiJSUzI1NiIsImtpZCI6ImQzN2FhNTA0MzgxMjkzN2ZlNDM5NjBjYTNjZjBlMjI4NGI2ZmMzNGQiLCJ0eXAiOiJKV1QifQ.eyJpc3MiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20iLCJhenAiOiIxMDU1NDgwNDA3NzY3LWZwcXRsMGRyOHYxbXVqZXJzMzlpcmNzbzJuc2txNmxjLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiYXVkIjoiMTA1NTQ4MDQwNzc2Ny1mcHF0bDBkcjh2MW11amVyczM5aXJjc28ybnNrcTZsYy5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsInN1YiI6IjExMTAzMDU5MzA4NTYyMzY2MTkzMSIsImVtYWlsIjoiZmItZHRhbGtlckBmb3htYWlsLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJhdF9oYXNoIjoiUUFw*****kyMVB0akp5ektfR2tfQSIsImlhdCI6MTY3Mzk0MTEzNiwiZXhwIjoxNjczOTQ0NzM2fQ.JBXdGyDce2R*****sqOoGw4D-rn9SXyv0ADK--aXB-5L4l-Wz43Y4MllcwlUA3eMtkUq_dJPR2z0jp93PkfS3MvMu_HciD_gl9xn65P2f5MI6PWwDEPyw4qo7ikkmTxwYB0ChXPPJOQ9UCJmXRyZCc7vuGyJYGpulK9BnEyHyU9tXnrXq79lunbIZJtHszoViEZZVVimaLc12WsvUBH5Kp-jRIWteQ8pHmkb5q01vRaSlb5l73OKmZBdyfHa06O68AtAEy2nOxqob1VeU7cZM6yLk5sOhHaTPF6G5HwQB9rYIdIR1g3aG-zYOvxs-vFpbM_CQmZKJbjMwbF2x3CyDA'
    }
    //为了账号安全加了*号
    */

    var userInfo = await verifyGoogleIdToken(id_token, GoogleConfig.client_id);
    console.log(userInfo);

    ctx.body = JSON.stringify(userInfo);
});

module.exports = router;

//参考链接：
//https://pyctw.medium.com/google-oauth-2-0-openid-connect-oidc-%E7%AC%AC%E4%B8%89%E6%96%B9%E7%99%BB%E5%85%A5%E5%AF%A6%E4%BD%9C-b2b48ea64a67
//https://developers.google.com/identity/openid-connect/openid-connect
//https://developers.google.com/gmail/api/reference/rest?apix=true